const alarmRecordRepository = require("../repositories/alarmRecordRepositories");

class AlarmRecordService {
  // 提取通用的响应处理函数
  handleResponse(data, error, notFoundMessage = "报警记录未找到") {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return {
      code: 0,
      msg: data,
    };
  }

  async getAllAlarmRecords() {
    try {
      const alarmRecords = await alarmRecordRepository.getAllAlarmRecords();
      return this.handleResponse(alarmRecords);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  async getAlarmRecordById(id) {
    try {
      const alarmRecord = await alarmRecordRepository.findById(id);
      return this.handleResponse(alarmRecord);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  async createAlarmRecord(alarmRecordData) {
    try {
      const newAlarmRecord = await alarmRecordRepository.create(
        alarmRecordData
      );
      return this.handleResponse(newAlarmRecord);
    } catch (error) {
      error.statusCode = 400; // 设置特定的状态码
      return this.handleResponse(null, error);
    }
  }

  async updateAlarmRecord(id, alarmRecordData) {
    try {
      const updatedAlarmRecord = await alarmRecordRepository.update(
        id,
        alarmRecordData
      );
      return this.handleResponse(updatedAlarmRecord);
    } catch (error) {
      error.statusCode = 400; // 设置特定的状态码
      return this.handleResponse(null, error);
    }
  }

  async delAlarmRecordById(id) {
    try {
      const result = await alarmRecordRepository.delAlarmRecordById(id);
      if (result) {
        return this.handleResponse("报警记录删除成功");
      } else {
        return this.handleResponse(null, null, "报警记录未找到");
      }
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }
}

module.exports = new AlarmRecordService();
